package com.jiangxjsy.admin.service.impl;

import com.jiangxjsy.admin.mapper.AdminUserRoleMapper;
import com.jiangxjsy.admin.service.AdminRoleAuthService;
import com.jiangxjsy.admin.service.AdminUserRoleService;
import com.jiangxjsy.model.admin.entity.AdminUserRole;
import com.jiangxjsy.model.core.entity.UserMeta;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/6/6 19:35
 */

@Service
public class AdminUserRoleServiceImpl implements AdminUserRoleService {
    @Resource
    private AdminUserRoleMapper adminUserRoleMapper;

    @Resource
    private AdminRoleAuthService adminRoleAuthService;

    /**
     * 根据用户 id 查询用户角色 id
     *
     * @param userId 用户 id
     * @return 角色 id 列表
     */
    @Override
    public List<Integer> queryUserRoleIds(Long userId) {
        return adminUserRoleMapper.selectByUserId(userId);
    }

    /**
     * 根据用户 id 查询用户角色数量
     *
     * @param userId 用户 id
     * @return 角色数量
     */
    @Override
    public Integer queryCountByUserId(Long userId) {
        return adminUserRoleMapper.selectCountByUserId(userId);
    }

    /**
     * 通过userID删除该用户的所有
     *
     * @param userId 用户ID
     * @param isRemove 是否删除原有角色
     * @param roleIds 角色列表
     * @param userMeta 用户元数据
     */
    @Override
    public void saveByUserId(Long userId, boolean isRemove, List<String> roleIds, UserMeta userMeta) {
        if (isRemove) {
            Integer ignore = adminUserRoleMapper.deleteByUserId(userId);
        }

        List<AdminUserRole> adminUserRoleList = new ArrayList<>();
        for (String roleId : roleIds) {
            AdminUserRole adminUserRole = new AdminUserRole();
            adminUserRole.setUserId(userId);
            adminUserRole.setRoleId(Long.valueOf(roleId));
            adminUserRoleList.add(adminUserRole);
        }

        boolean queryAllRole = adminRoleAuthService.isQueryAllRole(userMeta.getUserId());
        if(!queryAllRole){
            Set<Integer> authByUser = adminRoleAuthService.queryAuthByUser(userMeta.getUserId());
            adminUserRoleList.removeIf(userRole -> !authByUser.contains(Math.toIntExact(userRole.getRoleId())));
        }

        Integer ignore = adminUserRoleMapper.insertAdminUserRoleBatch(adminUserRoleList);
    }
}
